package org.emet.flex.util
{
	import flash.display.DisplayObject;
	
	import mx.collections.ArrayCollection;
	import mx.containers.Panel;
	import mx.containers.ViewStack;
	import mx.controls.Alert;
	import mx.formatters.DateFormatter;
	import mx.managers.PopUpManager;
	import mx.messaging.messages.ErrorMessage;
	import mx.rpc.events.FaultEvent;
	
	import org.emet.flex.web.view.MsgWin;
	
	public class CommonUtils
	{
		public function CommonUtils()
		{
			
		}
		
		public static function getCollectionItem(list:Array, keyField:String, keyValue:String) {
			for each(var item:Object in list) {
				if(item[keyField] == keyValue){
					return item;
				}
			}	
			return null;
		}
		public static function getItem(list:ArrayCollection, keyField:String, keyValue:Number) {
			for each(var item:Object in list) {
				if(item[keyField] == keyValue){
					return item;
				}
			}	
			return null;
		}
		public static function getItemByVal(list:ArrayCollection, valField:String, valValue:String) {
			for each(var item:Object in list) {
				if(item[valField] == valValue){
					return item;
				}
			}	
			return null;
		}
		
		// 异常处理
		public static function handlerError(parent:DisplayObject, e:FaultEvent):void
		{
			Alert.show(e.fault.faultString,"错误提示");
//			var errorMessage:ErrorMessage = e.message as ErrorMessage;
//			var w:MsgWin = PopUpManager.createPopUp(parent, MsgWin, true) as MsgWin;
//			w.shortMsg = errorMessage.faultString;
//			w.longMsg = errorMessage.faultDetail;
//			PopUpManager.centerPopUp(w); 
		}
		
		public static function showViewPanel(viewStack:ViewStack, viewName:String):void{
			var viewPanel:Panel = viewStack.getChildByName(viewName) as Panel;
			if(viewPanel != null){
				viewStack.selectedChild = viewPanel;
			}
		}
		
		//	var viewS:ViewStack = this.parent.parent as ViewStack;
		//	var dd:AddDeptView = new AddDeptView();
		//	dd.name = "helloxx";
		//	CommonUtils.addShowViewPanel(viewS,dd);
		public static function addShowViewPanel(viewStack:ViewStack, viewPanel:Panel):void{
			var viewPanel:Panel = viewStack.getChildByName(viewPanel.name) as Panel;
			if(viewPanel == null){
				viewStack.addChild(viewPanel);
			}
			viewStack.selectedChild = viewPanel;
		}
		
		public static function formatDate(date:Date,formatString:String = "YYYY-MM-DD"):String{
			var df:DateFormatter = new DateFormatter();
			df.formatString = formatString;
			return df.format(date);
		}
		
		public static function formatTime(date:Date,formatString:String = "JJ:NN"):String{
			return formatDate(date, formatString);
		}
		
		public static function formatDateTime(date:Date,formatString:String = "YY-MM-DD JJ:NN"):String{
			return formatDate(date, formatString);
		}
	}
}